package com.example.woh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.woh.entity.User;
import com.example.woh.exception.ArgumentException;
import com.example.woh.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sail
 * @since 2023-03-24
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {


    private final IUserService userService;

    @RequestMapping("/login")
    public ResponseEntity<String> login(String account,String password){
        boolean login = userService.login(account,password);
        if (login){
            return ResponseEntity.ok("success");
        }
        throw new ArgumentException("错了");
    }
    @GetMapping("/getUser")
    public ResponseEntity<User> getUser(String account){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",account);
        User user = userService.getOne(queryWrapper);
        return ResponseEntity.ok(user);
    }
    @GetMapping("/getUserById")
    public ResponseEntity<User> getUserById(Integer id){
        return ResponseEntity.ok(userService.getById(id));
    }


    @PostMapping ("/getUserList")
    @ResponseBody
    public ResponseEntity<List<User>> getUserList(@RequestBody Map<String, Object> requestMap){
        List<Integer> userIdList = (List<Integer>) requestMap.get("array");
        List<User> userList = new ArrayList<>();
        for (Integer id : userIdList) {
            User user = userService.getById(id);
            userList.add(user);
        }
        return ResponseEntity.ok(userList);
    }
    @GetMapping ("/getUserList")
    public ResponseEntity<List<User>> getUserList(Integer identity){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("identity",identity);
        List<User> userList = userService.list(queryWrapper);
        return ResponseEntity.ok(userList);
    }

    @PostMapping("/updatePassword")
    public ResponseEntity<String> updatePassword(String password,Integer id){
        User user = userService.getById(id);
        user.setPassword(password);
        if(userService.updateById(user)){
            return ResponseEntity.ok("更新成功");
        }
        throw new ArgumentException("更新密码错误");
    }



}
